﻿using Ljy_VoteSys.Models.Database;
using Ljy_VoteSys.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Ljy_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : Controller
    {
        //注入jwt服务
        private readonly IJWTService _jwtService;
        //定义数据库上下文
        private readonly Ljy_VoteSysContext _db;

        public LoginController(IJWTService jwtService, Ljy_VoteSysContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }
        //登录
        /// <summary>
        /// 普通用户登录?
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string LoginUserAccount(User request)
        {
            //登录 逻辑

            //校验用户

            //1、先把用户查询出来

            var user = _db.UserTables.FirstOrDefault(x => x.Username == request.Username);
            if (user == null)
                return "用户不存在";

            //2、校验密码
            var md5 = Md5.MD5Encrypt32(request.Pwd + user.Solt);
            if (user.Pwd != md5)
                return "密码不正确";

           
            return _jwtService.CreateToken(user.Username, 2612121);
        }

        /// <summary>
        /// 企业用户登录,,,
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string LoginCompanyUserAccount(CompanyUser request)
        {
            //登录 逻辑

            //校验用户

            //1、先把用户查询出来

            var user = _db.CompanyUsers.FirstOrDefault(x => x.CompanyUser1== request.CompanyUser1);
            if (user == null)
                return "用户不存在";

            //2、校验密码
            var md5 = Md5.MD5Encrypt32(request.Pwd + user.Solt);
            if (user.Pwd != md5)
                return "密码不正确";

            //都正确 确认是这个人
            return _jwtService.CreateToken(user.CompanyUser1, 2612121);
        }
  /// <summary>
        /// 测试token
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
      
        public string UserInfo()
        {
            //获取用户信息
            return Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value;
        }
    }
}

